package logic

import (
	"context"
	"fmt"
	"zhaowei/models/cache"
	"zhaowei/models/mysql"

	"zhaowei/baidurpc/baidurpc"
	"zhaowei/baidurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *baidurpc.LoginRequest) (*baidurpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该手机号未被注册")
	}
	mysql.DB.Debug().Find(&user)
	get, _ := cache.Rdb.Get(cache.Ctx, "sendsms"+in.Mobile).Result()
	if get != in.SendSms {
		return nil, fmt.Errorf("验证码错误")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误")
	}
	return &baidurpc.LoginResponse{
		Id: int64(user.ID),
	}, nil
}
